<?php

namespace app\store\controller;

use think\Controller;
use think\Db;
use think\Session;


/**
 * 请求代理服务器获取微信用户信息
 */
class Wauth extends Controller
{
    protected $shop_id      = 0;
    protected $appid        = "";
    protected $appsecret    = "";


    /**
     * 构造方法
     */
    public function __construct()
    {
        parent::__construct();

        $this->shop_id = input("shop_id",0);
        if($this->shop_id<=0){
            $this->error("店铺参数有误");
        }
        Session::set("shop_id",$this->shop_id);

        // 获取商户公众号配置信息
        $wx_config = Db("shops")->field("appid,appsecret")->where("shop_id",$this->shop_id)->find();

        $this->appid    = $wx_config['appid'];
        $this->appsecret= $wx_config["appsecret"];
    }


    /**
     * 获取code
     */
    public function getCode(){

   // 回调地址必填
        if(!input("call_back")){
            $this->error("回调地址参数不完整");
        }

        // 用户重要参数
        $params = http_build_query(input());

        // 获取用户信息跳转链接
        $redirecturl = urlencode(request()->domain().url('store/wauth/getUserInfo')."?".$params."&std=1");

        $snsapi_userInfo_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';

        $this->redirect($snsapi_userInfo_url);

    }


    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        $code = input('code');
        if(isset($code) && $code){

            // 通过code换取网页授权access_token
            $curl       = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';
            $content    = file_get_contents($curl);
            $result     = json_decode($content);

            // 通过access_token和openid拉取用户信息
            $webAccess_token    = $result->access_token;
            $openid             = $result->openid;
            $userInfourl        = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$webAccess_token.'&openid='.$openid.'&lang=zh_CN ';

            $recontent = file_get_contents($userInfourl);

            //用户信息
            $userInfo = json_decode($recontent,true);
            // 验证用户是否存在
            $u_info = Db::name('users')
                ->where('openid',$userInfo['openid'])
                ->find();
            // 用户已存在
            if(!empty($u_info) && isset($u_info)){
                // 写入缓存
                Session::set('openid',$userInfo['openid']);
                Session::set('uid',$u_info['uid']);
                // 用户首次访问
            }else{
                $params['nickname']     = $userInfo['nickname'];        // 微信昵称
                $params['openid']       = $userInfo['openid'];          // openid
                $params['sex']          = $userInfo['sex'];             // 性别 1男士 2女士
                $params['create_time']  = time();                       // 注册时间

                $in_id = Db::name('users')->insertGetId($params);

                Session::set('openid',$userInfo['openid']);
                Session::set('uid',$in_id);

            }


            // 将用户信息回调给请求人设置的回调地址
          //  $url = input("call_back").'?status=1&info='.$recontent;
            $url = input("call_back").'&status=1&info='.$recontent;

            $this->redirect($url);
        }

        die("<script>alert('Warning：服务器异常，稍后重试或联系管理员 !')</script>");
    }


}
